package com.xk857.simpleeffect.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.xk857.simpleeffect.R;
import com.xk857.simpleeffect.adapter.ListFriendAdapter;
import com.xk857.simpleeffect.db.PersonDataBase;
import com.xk857.simpleeffect.domain.Result;
import com.xk857.simpleeffect.domain.vo.FriendListVo;
import com.xk857.simpleeffect.enums.RequestEnum;
import com.xk857.simpleeffect.utils.OkHttpUtils;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xqrcode.util.QRCodeAnalyzeUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.toast.XToast;
import com.xuexiang.xutil.app.PathUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.lang.reflect.Type;
import java.util.List;
import java.util.function.Consumer;

public class FriendListActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_SCAN = 5;
    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 3;
    private static final int PICK_IMAGE_REQUEST = 7;
    private LinearLayout sweepLayout;
    private LinearLayout pictureLayout;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.white));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setContentView(R.layout.activity_friend_list);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        // 获取我的好友列表
        Type type = new TypeToken<Result<List<FriendListVo>>>() {}.getType();
        OkHttpUtils.getInstance().get(this, RequestEnum.GET_MY_FRIEND_LIST, type, true, (Consumer<List<FriendListVo>>) friendListVoList -> {
            runOnUiThread(() -> {
                LinearLayoutManager layoutManager = new LinearLayoutManager(this);
                recyclerView.setLayoutManager(layoutManager);
                ListFriendAdapter listFriendAdapter = new ListFriendAdapter(this, friendListVoList);
                listFriendAdapter.setItemAnimation(BaseQuickAdapter.AnimationType.AlphaIn);
                recyclerView.setAdapter(listFriendAdapter);
            });
        });
    }

    private void initView() {
        TitleBar titleBar = findViewById(R.id.title_bar);
        titleBar.setLeftClickListener(v -> finish());
        titleBar.addAction(new TitleBar.TextAction("邀请好友") {
            @Override
            public void performAction(View view) {
                startActivity(new Intent(FriendListActivity.this, ShareCodeActivity.class));
            }
        });
        sweepLayout = findViewById(R.id.sweep_layout);
        pictureLayout = findViewById(R.id.picture_layout);
        recyclerView = findViewById(R.id.recycler_view);

        sweepLayout.setOnClickListener(v -> XQRCode.startScan(this, REQUEST_CODE_SCAN));
        pictureLayout.setOnClickListener(v -> showFileChooser());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            // 处理二维码扫描结果
            handleScanResult(data);
        } else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
            // 用户选择图片识别二维码
            Uri imageUri = data.getData();
            getAnalyzeQRCodeResult(imageUri);
        }
    }

    // 处理二维码扫描结果
    private void handleScanResult(Intent data) {
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_SUCCESS) {
                    String result = bundle.getString(XQRCode.RESULT_DATA);
                    if (result.contains(PersonDataBase.ADD_FRIEND_KEY)) {
                        // 添加好友
                        result = result.replace(PersonDataBase.ADD_FRIEND_KEY, "");
                        sendAddFriend(result);
                    }
                } else if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_FAILED) {
                    XToast.info(this, "解析失败").show();
                }
            }
        }
    }

    private void sendAddFriend(String code) {
        Type type = new TypeToken<Result<Boolean>>() {
        }.getType();
        String url = OkHttpUtils.BASE_URL + "/api/v1/friendship/add?code=" + code;
        OkHttpUtils.getInstance().get(this, url, type, false, (Consumer<Boolean>) b -> {
            if (b) {
                runOnUiThread(() -> {
                    XToast.success(this, "好友添加成功").show();
                    initData();
                });
            }
        });
    }

    private void showFileChooser() {
        // 如果当前用户没给权限，则弹出权限申请
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        } else {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/**");
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 执行打开相册的操作
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, PICK_IMAGE_REQUEST);
            } else {
                if (this != null) {
                    new MaterialDialog.Builder(this).iconRes(R.drawable.icon_error_24).title(R.string.error)
                            .content("您拒绝了系统获取文件的权限，请前往设置打开‘读写手机存储’权限")
                            .positiveText(R.string.yes).onPositive((dialog, which) -> {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.fromParts("package", this.getPackageName(), null));
                                startActivity(intent);
                            }).show();
                }
            }
        }
    }

    private void getAnalyzeQRCodeResult(Uri uri) {
        XQRCode.analyzeQRCode(PathUtils.getFilePathByUri(this, uri), new QRCodeAnalyzeUtils.AnalyzeCallback() {
            @Override
            public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                if (result.contains(PersonDataBase.ADD_FRIEND_KEY)) {
                    // 添加好友
                    result = result.replace(PersonDataBase.ADD_FRIEND_KEY, "");
                    sendAddFriend(result);
                }
            }

            @Override
            public void onAnalyzeFailed() {
                ToastUtils.toast("解析二维码失败", Toast.LENGTH_LONG);
            }
        });
    }
}